package com.dlut.txy.designpattern.schedule.executor;

import com.dlut.txy.designpattern.schedule.task.ScheduleTask;
import com.dlut.txy.designpattern.schedule.task.TaskStatus;
import com.dlut.txy.designpattern.schedule.taskunit.impl.DelayQueueTaskUnit;
import com.dlut.txy.designpattern.schedule.taskunit.TaskUnit;
import com.dlut.txy.designpattern.schedule.taskunit.impl.ThreadTaskUnit;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public abstract class ScheduleExecutor {
    protected Map<String, TaskUnit> taskMap = new HashMap<>();
    public abstract ScheduleExecutor addTask(ScheduleTask scheduleTask, int scheduleMills);
    public abstract void runTask(String taskId);

    public ScheduleExecutor runAll() {
        for (String taskId : taskMap.keySet()) {
            runTask(taskId);
        }
        return this;
    }
    public void stopTask(String taskId) {
        if(taskMap.containsKey(taskId) && taskMap.get(taskId)!=null) {
            TaskUnit taskUnit = taskMap.get(taskId);
            if(taskUnit instanceof ThreadTaskUnit) {
                ThreadTaskUnit threadTaskUnit = (ThreadTaskUnit) taskUnit;
                if(threadTaskUnit.getStatus() == TaskStatus.STOP) {
                    return;
                }
                threadTaskUnit.getCurThread().interrupt();
                threadTaskUnit.setStatus(TaskStatus.STOP);
                taskMap.remove(taskId);
            } else if(taskUnit instanceof DelayQueueTaskUnit) {
                log.info("这里管不了，要在子类自己实现");
            } else {
                log.warn("不支持的任务类型");
            }
        }
    }
    public void stopAll() {
        for (String taskId : taskMap.keySet()) {
            stopTask(taskId);
        }
    }

    public enum Type {
        THREAD("thread","多线程方式"),
        DELAY_QUEUE("delay queue","延迟队列方式"),
        ;
        private String value;
        private String desc;
        Type(String value, String desc) {
            this.value = value;
            this.desc = desc;
        }
    }
}
